package com.jimmy.medical.service.impl;

import com.jimmy.medical.base.impl.JpaSpecificationServiceImpl;
import com.jimmy.medical.entity.*;
import com.jimmy.medical.enums.RechargeTypeEnum;
import com.jimmy.medical.model.ContractService;
import com.jimmy.medical.model.MemberService;
import com.jimmy.medical.model.SingleService;
import com.jimmy.medical.repository.*;
import com.jimmy.medical.service.IPersonalService;
import com.jimmy.medical.service.ISaleService;
import com.jimmy.medical.util.CommonUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

@Service
public class PersonalServiceImpl extends JpaSpecificationServiceImpl<FlowOrderRepository, FlowOrderRepository, FlowOrder, Long> implements IPersonalService {

    @Autowired
    RechargeRecordRepository rechargeRecordRepository;
    @Autowired
    FlowOrderRepository flowOrderRepository;
    @Autowired
    UserRepository userRepository;

    @Override
    public int saleToday(Long userId) {
        return rechargeRecordRepository.countByUser(userId, CommonUtils.getNowDateShortString());
    }

    @Override
    public int serviceToday(Long userId) {
        return flowOrderRepository.countByUser(userId, CommonUtils.getTodayTimeZero(), (short)1);
    }

    @Override
    public Double moneyToday(Long userId) {
        Double serviceMoney = flowOrderRepository.sumByUser(userId, CommonUtils.getTodayTimeZero(), (short)1);
        Double saleMoney = rechargeRecordRepository.sumByUser(userId, CommonUtils.getNowDateShortString());

        if(serviceMoney == null) {
            serviceMoney = 0D;
        }

        if(saleMoney == null) {
            saleMoney = 0D;
        }

        return serviceMoney + saleMoney;
    }

    @Override
    public Double moneyMonth(Long userId) {
        Double serviceMoney = flowOrderRepository.sumByUser(userId, CommonUtils.getFirstDayOfMonth(), (short)1);
        Double saleMoney = rechargeRecordRepository.sumByUser(userId, CommonUtils.getFirstDayOfMonthStr());

        if(serviceMoney == null) {
            serviceMoney = 0D;
        }

        if(saleMoney == null) {
            saleMoney = 0D;
        }

        return serviceMoney + saleMoney;
    }

    @Override
    public List<RechargeRecord> getRechargeRecordList(Long userId) {
        return rechargeRecordRepository.findAllBySaleUser(userId);
    }

    @Override
    public List<FlowOrder> getFlowOrderList(Long userId) {
        User user = userRepository.findOne(userId);
        return flowOrderRepository.findAllByUserAndIsFinishOrderByCreateTimeDesc(user, (short)1);
    }
}
